import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    const token = userStore.token
    
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 防止重复调用logout的标志
let isLoggingOut = false

// 响应拦截器
request.interceptors.response.use(
  response => {
    const { data } = response
    
    // 如果后端返回的数据结构包含code和message
    if (data.code !== undefined) {
      if (data.code === 200) {
        return data
      } else if (data.code === 401) {
        // 未授权，跳转到登录页
        if (!isLoggingOut) {
          isLoggingOut = true
          const userStore = useUserStore()
          userStore.logout().finally(() => {
            isLoggingOut = false
          })
          router.push('/login')
          ElMessage.error('登录已过期，请重新登录')
        }
        return Promise.reject(new Error(data.message || '未授权'))
      } else {
        ElMessage.error(data.message || '请求失败')
        return Promise.reject(new Error(data.message || '请求失败'))
      }
    }
    
    return data
  },
  error => {
    console.error('响应错误:', error)
    
    if (error.response) {
      const { status } = error.response
      
      switch (status) {
        case 401:
          if (!isLoggingOut) {
            isLoggingOut = true
            const userStore = useUserStore()
            userStore.logout().finally(() => {
              isLoggingOut = false
            })
            router.push('/login')
            ElMessage.error('登录已过期，请重新登录')
          }
          break
        case 403:
          ElMessage.error('没有权限访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error('网络错误，请稍后重试')
      }
    } else {
      ElMessage.error('网络连接失败')
    }
    
    return Promise.reject(error)
  }
)

export default request 